<template>
  <el-card class="roles-page">
    <div class="header">
      <div class="add">
        <el-button type="success" class="el-icon-edit" @click="add"
          >新增菜单</el-button
        >
      </div>
    </div>

    <el-table
      :header-cell-style="{ background: '#FAFAFA' }"
      :data="menusData"
      style="width: 100%; margin-top: 20px"
      row-key="id"
      border
      default-expand-all
      :tree-props="{ children: 'childs' }"
    >
      <el-table-column prop="title" label="标题" width="200">

         </el-table-column>
      <el-table-column prop="code" label="权限点代码" width="600">
      </el-table-column>

      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button
            circle
            plain
            type="primary"
            icon="el-icon-edit"
            @click="edit(scope.row)"
          ></el-button>
          <el-button
            circle
            plain
            type="danger"
            icon="el-icon-delete"
            @click="del(scope.row)"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- <div class="pagination">
      <el-pagination
        background
        layout="prev, pager, next,sizes,jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page.sync="params.page"
        :page-sizes="[10, 20, 30, 50]"
        :total="counts"
      >
      </el-pagination>
    </div> -->
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      width="50%"
      :close-on-click-modal="false"
    >
      <div v-if="isAdd">
        <el-form
          ref="formRef"
          :model="menusForm"
          :rules="rules"
          label-width="100px"
        >
          <el-form-item label="权限组名称">
            <el-radio v-model="menusForm.is_point" label="0">菜单</el-radio>
            <el-radio v-model="menusForm.is_point" label="1">权限点</el-radio>
          </el-form-item>
          <el-form-item label="权限组名称">
            <el-select
              v-model="menusForm.pid"
              placeholder="请选择"
              filterable
              clearable
               @clear="handleClear"

              ref="selectUpResId"
            >
              <el-option
                hidden
                key="menusForm.pid"
                :value="menusForm.pid"
                :label="upResName"
              >
              </el-option>
              <el-tree
                :data="menusTrees"
                :props="defaultProps"
                default-expand-all
                @node-click="handleNodeClick"
              >
              </el-tree>
            </el-select>
          </el-form-item>

          <el-form-item label="权限代码" prop="code">
            <el-input v-model="menusForm.code"></el-input>
          </el-form-item>
          <el-form-item label="权限标题" prop="title">
            <el-input v-model="menusForm.title"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div v-if="isEdit">
        <el-form
          ref="formRef"
          :model="menusForm"
          :rules="rules"
          label-width="100px"
        >
          <el-form-item label="权限组名称">
            <el-radio v-model="menusForm.is_point" label="0" disabled
              >菜单</el-radio
            >
            <el-radio v-model="menusForm.is_point" label="1" disabled
              >权限点</el-radio
            >
          </el-form-item>
             <el-form-item label="权限组名称">
            <el-select
              v-model="menusForm.pid"
              placeholder="请选择"
              filterable
              clearable
               @clear="handleClear"

              ref="selectUpResId"
            >
              <el-option
                hidden
                key="menusForm.pid"
                :value="menusForm.pid"
                :label="upResName"
              >
              </el-option>
              <el-tree
                :data="menusTrees"
                :props="defaultProps"
                default-expand-all
                @node-click="handleNodeClick"
              >
              </el-tree>
            </el-select>
          </el-form-item>

          <el-form-item label="权限代码" prop="code">
            <el-input v-model="menusForm.code"></el-input>
          </el-form-item>
          <el-form-item label="权限标题" prop="title">
            <el-input v-model="menusForm.title"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </span>
    </el-dialog>
  </el-card>
</template>

<script>
import { menusList, add, detail, update, remove } from '@/api/base/menus'

export default {
  data () {
    const checkName = (rule, value, callback) => {
      let arr // 把这个放在if else的外面 就保证这块的arr只有一个
      // 把当前这个节点所有的子部门拿过来了
      if (this.title === '创建菜单') {
        arr = this.temporaryData.filter(item => item.pid === this.menusForm.pid)
      } else {
        // arr 代表当前这个节点所有的兄弟部门
        // 编辑当前部门规则：先把自己这个部门所有的兄弟部门找到，然后你修改之后部门名字不能重复（可以和自己一样）
        arr = this.temporaryData.filter(item => item.pid === this.menusForm.pid && item.id !== this.menusForm.id)
      }
      if (arr.some(item => item.name === value)) {
        callback(new Error(`同级部门已经有${value}的部门了`))
      } else {
        callback()
      }
    }
    const checkCode = (rule, value, callback) => {
      let arr // 把这个放在if else的外面 就保证这块的arr只有一个
      // 把当前这个节点所有的子部门拿过来了
      if (this.title === '创建菜单') {
        arr = this.temporaryData.filter(item => item.pid === this.menusForm.id)
      } else {
        // arr 代表当前这个节点所有的兄弟部门
        // 编辑当前部门规则：先把自己这个部门所有的兄弟部门找到，然后你修改之后部门名字不能重复（可以和自己一样）
        arr = this.temporaryData.filter(item => item.pid === this.menusForm.pid && item.id !== this.node.id)
      }

      if (arr.some(item => item.code === value)) {
        callback(new Error(`组织架构中已经有${value}编码了`))
      } else {
        callback()
      }
    }
    return {
      // formInline: {
      //   username: ''
      // },
      // params: {
      //   page: 1,
      //   pagesize: 10,
      //   username: ''
      // },
      menusForm: {
        is_point: '0',
        pid: '',
        code: '',
        title: ''
      },
      type: '',
      menusData: [],
      counts: null,

      dialogVisible: false,
      title: '',
      isAdd: false,
      isEdit: false,
      menusTrees: [],
      temporaryData: [], // 临时
      upResName: '',

      defaultProps: {
        children: 'childs',
        label: 'title'
      },
      rules: {
        code: [{ required: true, message: '代码不能为空', trigger: 'blur' },
          { validator: checkCode, trigger: 'blur' }
        ],
        title: [{ required: true, message: '标题不能为空', trigger: 'blur' },
          { validator: checkName, trigger: 'blur' }]
      }
    }
  },
  created () {
    this.menusList()
  },
  methods: {
    onSubmit () {
      this.params.username = this.formInline.username

      this.menusList()
    },
    async menusList () {
      const { data } = await menusList(this.params)

      const Array = JSON.parse(
        JSON.stringify(data).replace(/points/g, 'childs')
      )

      // 为其添加一个父节点
      const newArray = []
      const result = {
        id: 1,
        title: '主导航',
        childs: [...Array]
      }
      newArray.push(result)

      const newData = []
      function transilatef (data) {
        data.forEach(item => {
          const newObj = {}
          newObj.id = item.id
          newObj.title = item.title
          newData.push(newObj)
          if (item.childs && item.childs.length > 0) {
            return transilatef(item.childs)
          }
        })
      }
      transilatef(newArray)

      this.temporaryData = newData

      this.menusData = Array
      this.menusTrees = newArray
    },

    handleSizeChange (val) {
      this.params.pagesize = val
      this.menusList()
    },
    handleCurrentChange (current) {
      this.params.page = current
      this.menusList()
    },
    // 节点点击事件
    handleNodeClick (data) {
      this.upResName = data.title
      this.menusForm.pid = data.id
      // 选择器执行完成后，使其失去焦点隐藏下拉框的效果
      this.$refs.selectUpResId.blur()
    },
    // 选择器配置可以清空选项，用户点击清空按钮时触发
    handleClear () {
      // 将选择器的值置空
      this.upResName = ''
      this.menusForm.pid = ''
    },
    add () {
      this.title = '创建菜单'
      this.dialogVisible = true
      this.isAdd = true
      this.isEdit = false
      this.type = Boolean(+this.menusForm.is_point)
    },
    async edit (row) {
      this.title = '编辑菜单'
      this.dialogVisible = true
      this.isAdd = false
      this.isEdit = true
      const { data } = await detail(row)

      this.menusForm.is_point = data.is_point
      this.menusForm.pid = data.pid
      this.temporaryData.forEach(item => {
        if (item.id === data.pid) {
          this.upResName = item.title
        } else {
          this.upResName = '主导航'
        }
      })
      this.menusForm.code = data.code
      this.menusForm.title = data.title
      // this.menusForm.role = data.role
      this.menusForm.id = data.id

      // this.menusForm.phone = data.phone
      // this.menusForm.introduction = data.introduction
    },
    async save () {
      try {
        if (this.title === '创建菜单') {
          await this.$refs.formRef.validate()
          const res = await add({
            code: this.menusForm.code,
            is_point: this.type,
            pid: this.menusForm.pid,
            title: this.menusForm.title
          })

          if (res.status === 200) {
            this.$message.success('添加成功')
          } else {
            this.$message.error('添加失败')
          }
        } else {
          const res = await update(this.menusForm)
          if (res.status === 200) {
            this.$message.success('修改成功')
          } else {
            this.$message.error('修改失败')
          }
        }
        this.dialogVisible = false
        this.menusList()
      } catch (err) {
        this.$message.error(err.response.data)
      }
    },
    async del (row) {
      await this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      await remove(row)
      this.$message({
        type: 'success',
        message: '删除成功!'
      })
      this.menusList()
    }
  }
}
</script>

<style scoped lang="scss">
.roles-page {
  margin: 20px 20px;
  .header {
    display: flex;
    justify-content: flex-end;
  }

  .pagination {
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
  }
  .el-dialog {
    .dialog-footer {
      display: block;
      text-align: center;
    }
  }
  //有子节点 且未展开
.el-tree ::v-deep .el-tree-node__expand-icon.expanded
{
    -webkit-transform: rotate(0deg);
    transform: rotate(0deg);
}
//有子节点 且未展开
.el-table ::v-deep .el-icon-arrow-right:before {
  background: url('~@/assets/logo.png') no-repeat 0 3px;
  content: '';
  display: block;
  width: 16px;
  height: 16px;
  font-size: 16px;
  background-size: 16px;
}
//有子节点 且已展开
.el-table::v-deep .el-table__expand-icon--expanded {
  .el-icon-arrow-right:before {
    background: url('~@/assets/401_images/401.gif') no-repeat 0 3px;
    content: '';
    display: block;
    width: 15px;
    height: 20px;
    font-size: 18px;
    background-size: 21px;
  }
}
//没有子节点
.el-tree ::v-deep.el-tree-node__expand-icon.is-leaf::before
.el-table::v-deep.el-table__placeholder::before {
  background: url('~@/assets/logo.png') no-repeat 0 3px;
  content: '';
  display: block;
  width: 16px;
  height: 18px;
  font-size: 16px;
  background-size: 16px;
}

}
</style>
